/**   
 *    
 * 项目名称：SmartKungFu   
 * 类名称：MstMessageServiceImpl   
 * 类描述：   
 * 创建人：Wdd   
 * 创建时间：2016年10月31日 上午10:43:58   
 * 修改人：Wdd  
 * 修改时间：2016年10月31日 上午10:43:58   
 * 修改备注：   
 * @version    
 *    
 */
package com.lst.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.http.ProtocolType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.aliyuncs.push.model.v20160801.PushRequest;
import com.aliyuncs.push.model.v20160801.PushResponse;
import com.github.miemiedev.mybatis.paginator.domain.PageBounds;
import com.lst.common.CommonEnum;
import com.lst.common.JPushEnum;
import com.lst.common.JPushMessage;
import com.lst.dao.ClientAccomplishMapper;
import com.lst.dao.ClientGrowthMapper;
import com.lst.dao.MstClientMapper;
import com.lst.dao.MstGradeMapper;
import com.lst.dao.MstMessageMapper;
import com.lst.model.ClientAccomplish;
import com.lst.model.MstClient;
import com.lst.model.MstMessage;
import com.lst.model.MstUser;
import com.lst.service.MstMessageService;
import com.lst.utils.DateUtil;

/**
 * @ClassName: MstMessageServiceImpl
 * @Description: 系统消息
 * @author Wdd
 * @date 2016年10月31日 上午10:43:58
 * 
 */
@Service("mstMessageServiceImpl")
public class MstMessageServiceImpl implements MstMessageService {

    private Logger logger = Logger.getLogger("log");

    @Autowired
    private MstMessageMapper dao;

    @Autowired
    private ClientGrowthMapper clientGrowthMapper;

    @Autowired
    private MstClientMapper mstClientMapper;

    @Autowired
    private MstGradeMapper mstGradeMapper;
    
    @Autowired
    private ClientAccomplishMapper clientAccomplishMapper;

    @Override
    public int deleteByPrimaryKey(Integer id) {
	return dao.deleteByPrimaryKey(id);
    }

    @Override
    public int insert(MstMessage record) {
	return dao.insert(record);
    }

    @Override
    public int insertSelective(MstMessage record) {
	return dao.insertSelective(record);
    }

    @Override
    public MstMessage selectByPrimaryKey(Integer id) {
	return dao.selectByPrimaryKey(id);
    }

    @Override
    public int updateByPrimaryKeySelective(MstMessage record) {
	return dao.updateByPrimaryKeySelective(record);
    }

    @Override
    public int updateByPrimaryKey(MstMessage record) {
	return dao.updateByPrimaryKey(record);
    }

    @Override
    public List<MstMessage> queryByList(Map<String, Object> map,
	    PageBounds pageBounds) {
	return dao.queryByList(map, pageBounds);
    }

    /**
     * 发送消息
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void pushMessage(String grade, String content,String reserved10,
	    MstUser sysUser) {
	Date startDate = new Date();
	logger.info("pushMessage begin: " + startDate);
	
	IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", "LTAIm6erYnqovyO5", "72fmEMX8AbdwXJOoyGPhkELXT002Ft");
	DefaultAcsClient client = new DefaultAcsClient(profile);

	PushResponse rsp = new PushResponse();

	try {
	    // 推送消息
		PushRequest iOSRequest = new PushRequest ();
		
		iOSRequest.setProtocol(ProtocolType.HTTPS);
        iOSRequest.setMethod(MethodType.POST);
	    iOSRequest.setAppKey(new Long("23560261"));// appkey
	    iOSRequest.setPushType("NOTICE"); // 消息类型：通知
        iOSRequest.setiOSApnsEnv("DEV"); // iOS的通知是通过APNS中心来发送的，需要填写对应的环境信息. DEV :表示开发环境, PRODUCT: 表示生产环境
        iOSRequest.setiOSBadge(1); // iOS应用图标右上角角标
        iOSRequest.setiOSMusic("default"); // iOS通知声音
        iOSRequest.setDeviceType("iOS"); 
        iOSRequest.setTitle("");
        iOSRequest.setBody(content);
        iOSRequest.setiOSExtParameters("{\"type\":\"notice\"}");

	    if (StringUtils.hasText(grade)) {
		/**
		 * 按功夫等级推送
		 */
		Map<String, Object> reqMap = new HashMap<String, Object>();
		PageBounds pageBounds = new PageBounds();

		// 查询用户
		reqMap.clear();
		reqMap.put("isDeleted", 0);
		reqMap.put("enabled", 1);
		reqMap.put("orderByClause", "u.createdate desc");

		List<MstClient> mstClientList = mstClientMapper.queryByList(
			reqMap, pageBounds);

		// 要推送的用户List
		List<MstClient> pushClientList = new ArrayList<>();

		for (MstClient mstClient : mstClientList) {
			
			//查询用户成就
			List<ClientAccomplish> calist = new ArrayList<>();
			calist = clientAccomplishMapper.queryByUser(mstClient.getId());
			
			if (calist.size() > 0) {
				ClientAccomplish clientAccomplish = calist.get(0);
				
				if((clientAccomplish.getGrade().toString()).equals(grade)){
					pushClientList.add(mstClient);
				}
			}
		}

		String targetValue = "";
		// 推送部分用户
		iOSRequest.setTarget("ACCOUNT");
		
		int tag = 0;
				
		for (MstClient mstClient : pushClientList) {
			tag ++;
		    if (targetValue.equals("")) {
			targetValue += mstClient.getId();
		    } else {
			targetValue += ("," + mstClient.getId());
		    }
		    //一次不能大于100个用户
		    if(tag == 100){
		    	iOSRequest.setTargetValue(targetValue);
		    	rsp = client.getAcsResponse(iOSRequest);
		    	tag = 0;
		    	targetValue = "";
		    }
		}
		
		if(tag > 0 && tag < 100){
			iOSRequest.setTargetValue(targetValue);
			rsp = client.getAcsResponse(iOSRequest);
		}
	    } else {
		// 推送所有用户
	    iOSRequest.setTarget("ALL");
	    iOSRequest.setTargetValue("all");

	    rsp = client.getAcsResponse(iOSRequest);
	    }

	    // 推送成功后插入消息
	    saveInfo(content, sysUser, reserved10);
	} catch (ClientException e) {
	    logger.error("pushMessage error:", e);
	}

	logger.info("pushMessage end run(s): "
		+ DateUtil.calLastedTime(startDate));
    }

    /**
     * 添加消息
     */
    @Override
    public void saveInfo(String content, MstUser sysUser,String reserved10) {
	Date startDate = new Date();
	logger.info("saveInfo begin: " + startDate);

	try {
	    MstMessage mstMessage = new MstMessage();

	    mstMessage.setContent(content);
	    mstMessage.setType(CommonEnum.SYSCODE_MSG_TYPE_PUSH);
	    mstMessage.setSendtype(CommonEnum.SYSCODE_MSG_SEND_TYPE_USER);
	    mstMessage.setReceivetype(CommonEnum.SYSCODE_MSG_RECEIVE_TYPE_CLIENT);
	    mstMessage.setSendid(sysUser.getId());
	 //   mstMessage.setReserved1(StringUtils.hasText(grade) ? Integer.parseInt(grade) : null);

	    mstMessage.setCreatedate(startDate);
	    mstMessage.setCreateuser(sysUser.getId());
	    mstMessage.setEnabled(true);
	    mstMessage.setIsdeleted(false);
	    mstMessage.setReserved10(reserved10);
	    mstMessage.setReserved2(1);
	    mstMessage.setReserved7(false);

	    dao.insert(mstMessage);
	    
	    List<String> strList=new ArrayList<String>();
	    Map<String,Object> map=new  HashMap<String, Object>();
	    map.put("systemStatus", 1);
	    List<MstClient> mstClientList=mstClientMapper.queryByList2(map);
	    if(mstClientList!=null){
	    	for(MstClient mstClient:mstClientList){
	    		String str="alias_"+mstClient.getId();
	    		strList.add(str);
	    	}
	    }
	    JPushMessage.pushMessage(mstMessage, JPushEnum.ALL_ALIAS,strList);
	    
	} catch (Exception e) {
	    logger.error("saveInfo error:", e);
	}

	logger.info("saveInfo end run(s): " + DateUtil.calLastedTime(startDate));
    }
}
